/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Input, InputNumber, notification, Popconfirm, Select, Switch, Table} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import styles from "../../index.less";
import ViewTitle from "../../../components/ViewTitle";
import ModalCreateOrEditContact from "./ModalCreateOrEditContact";
import customer from "../../../models/customer";
import UploadPic from "../../../components/UploadPic";

moment.locale('zh-cn');
const table = 'Customer';
@Form.create()
@connect(({user, global, dict, customer}) => ({...user, ...customer, ...dict, ...global}))
export default class ModalCreateOrEditCustomer extends FormBase {
  constructor(props) {
    super(props);
    this.state = undefined;
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'industry'}
    });
  }

  renderFoot = () => {
    const {foot, value, modalRef, callback, form} = this.props;
    const model = this.props[`${table}Model`];
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              _.map(model, (item, key) => {
                if (key !== 'labels' && values[key]) {
                  const {key, inputType} = item;
                  const _v = values[key];
                  let value = inputType.toLowerCase() === 'date' ? moment(_v).format('YYYY-MM-DD') : _v;
                  value = inputType.toLowerCase() === 'time' ? moment(_v).format('YYYY-MM-DD hh:mm:ss') : value;
                  values[key] = value;
                }
              });

              const {labels} = model;
              const _labels = [];

              _.map(labels, item => {
                const {key, inputType, selectOption} = item;
                let _v = values[key];
                const json = {};
                json[key] = _v;
                if (_v && inputType.toLowerCase() === 'select') {
                  const v = _.find(selectOption, item => item.value === _v);
                  const value = v ? v.label : _v;
                  json[key] = value;
                }
                if (_v && inputType.toLowerCase() === 'date') {
                  json[key] = moment(_v).format('YYYY-MM-DD');
                }
                _labels.push(json);
              });
              values.labels = _labels;
              const {contactList = [], fileList, industry} = this.state;
              values.contactList = contactList;
              values.industry = industry;
              values.fileList = fileList;
              callback(values);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  onCreateOrEdit = values => {
    ModalView.open(ModalCreateOrEditContact, {
      title: "联系方式",
      width: '920px'
    }, {
      values,
      callback: (record) => {
        const {contactList = []} = this.state;
        if (values) {
          contactList.forEach((item, index) => {
            if (item.code === record.code) {
              contactList[index] = record;
            }
          });
        } else {
          contactList.push(record);
        }
        this.setState({contactList});
      }
    });
  };

  cols() {
    return [{
      title: '客户地址',
      dataIndex: 'address',
      key: 'address'
    },
      {
        title: '联系人',
        dataIndex: 'contacts',
        key: 'contacts'
      },
      {
        title: '联系电话',
        dataIndex: 'contactsPhone',
        key: 'contactsPhone'
      },
      {
        title: '职务',
        dataIndex: 'position',
        key: 'position'
      },
      {
        title: '操作',
        dataIndex: 'opt',
        key: 'opt',
        render: (value, record) => {
          return <span>
              {<a style={{marginRight: '6px'}}
                  onClick={() => this.onCreateOrEdit(record)}
              >编辑</a>}
            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                const {contactList = []} = this.state;
                const {code} = record;
                _.remove(contactList, item => {
                  return item.code === code;
                });
                this.setState({contactList});
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>}
            </span>;
        }
      }
    ];
  }

  render() {
    const {form, footDisabled, style, values = {}, cols = 2, industryDict = []} = this.props;

    if (this.state === undefined || this.state === null) {
      this.state = {...values};
    }
    const {contactList = [], fileList = []} = this.state;
    const {code = this.getCode('CUS'), industry, name} = values;
    return (
      <div style={{...style}}>
        {<FormLayout form={form} cols={cols}>
          <FormField
            label={'客户编码'}
            name={'code'}
            required={true}
            initialValue={code}
          >
            <Input disabled style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'客户名称'}
            name={'name'}
            required={true}
            initialValue={name}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'行业'}
            name={'industry'}
            initialValue={industry}
          >
            <Select allowClear placeholder="请选择" style={{width: '100%'}}
                    onChange={value => {
                      this.state.industry = value;
                    }}
            >
              {this.getDivision(industryDict)}
            </Select>
          </FormField>
        </FormLayout>}
        <ViewTitle
          title={`联系方式列表`}
          level={1}
          actions={[
            <Button type="primary" onClick={() => this.onCreateOrEdit()}>添加</Button>
          ]
          }></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.cols()}
          dataSource={contactList}
          scroll={{x: true}}
          pagination={true}
          //scroll={{ x: 1300 }}
        ></Table>
        <UploadPic
          title={'上传开票资料'} fileList={fileList}
          callback={f => {
            this.state.fileList = f.fileList;
          }}
        ></UploadPic>
        {!footDisabled && this.renderFoot()}
      </div>

    );
  }
}

